﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Blade.Devices.Storage;
using System.IO;

namespace Blade.DiskEdit {
	public class DiskImageDevice : IStorageDevice {
		public DiskImageDevice(FileStream stream, int blockSize)
			: this(stream, blockSize, stream.Name) {
		}

		public DiskImageDevice(Stream stream, int blockSize, string filename) {
			this.Stream = stream;
			this.BlockSize = blockSize;
			this.FileName = filename;
		}

		public int BlockSize { get; private set; }
		public Stream Stream { get; private set; }
		public string FileName { get; private set; }
		public long BlockCount { get { return Stream.Length / BlockSize; } }

		public void ReadBlock(long index, byte[] block, int offset) {
			if (block == null)
				throw new ArgumentNullException("block");
			if (block.Length < BlockSize)
				throw new ArgumentOutOfRangeException("block.Length");
			Stream.Seek(index * BlockSize, SeekOrigin.Begin);
			int read = Stream.Read(block, offset, BlockSize);
			if (read != BlockSize)
				throw new IOException();
		}

		public static DiskImageDevice Create(string filename, int blockSize, long blockCount) {
			var stream = File.Open(
				filename,
				FileMode.Create,
				FileAccess.ReadWrite,
				FileShare.Read
			);
			stream.SetLength(blockSize * blockCount);
			return new DiskImageDevice(stream, blockSize);
		}
	}
}
